package com.heima.wemedia.service.impl;

import com.heima.common.constants.ScheduleConstants;
import com.heima.feign.client.ScheduleFeignClient;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private ScheduleFeignClient scheduleFeignClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;
    /**
     * 添加任务接口
     *
     * @param newsId
     * @param publishTime
     */
    @Override
    @Async
    public void saveNewsToTask(Long newsId, Date publishTime) {
        Task task=new Task();
        task.setExecuteTime(publishTime.getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        //关于序列化成字节数组，两种方式，第一使用string，第二使用工具类
        WmNews wmNews=new WmNews();
        wmNews.setId(newsId.intValue());
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        scheduleFeignClient.addTask(task);
    }

    @Override
    @Scheduled(fixedRate = 50000)//每50s执行一次
    @SneakyThrows
    public void pullTask() {
        //远程调用接口
        Task task = scheduleFeignClient.pull(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(task!=null && task.getParameters().length>0){
            byte[] bytes = task.getParameters();
            //反序列化
            WmNews wmNews = ProtostuffUtil.deserialize(bytes, WmNews.class);

            //调用自动审核业务
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId().intValue());
        }else{
            log.warn("任务为空,没有新的任务");
        }

    }
}
